package com.aikon.wht.concurrent;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author haitao.wang
 */
public class TestOfSyncCompareWithLock {
    private static Object lock = new Object();

    private static Lock reentrantLock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        sync();
//        lock();
    }

    private static void sync() throws InterruptedException {
        int N = 10;
        Thread[] threads = new Thread[N];
        for (int i = 0; i < N; ++i) {
            threads[i] = new Thread(() -> {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + " get sync lock!");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        synchronized (lock) {
            for (int i = 0; i < N; ++i) {
                threads[i].start();
                Thread.sleep(200);
            }
        }

        for (int i = 0; i < N; ++i)
            threads[i].join();
    }

    private static void lock() throws InterruptedException {
        int N = 10;
        Thread[] threads = new Thread[N];
        for (int i = 0; i < N; ++i) {
            threads[i] = new Thread(() -> {
                reentrantLock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " get reEntrant lock!");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    reentrantLock.unlock();
                }
            });
        }
        reentrantLock.lock();
        try {

            for (int i = 0; i < N; ++i) {
                threads[i].start();
                Thread.sleep(200);
            }
        } finally {
            reentrantLock.unlock();
        }

        for (int i = 0; i < N; ++i)
            threads[i].join();

    }
}
